App.require(["canvasTool"], function (canvasTool) {
    function Pattern(parent) {
        this.parent = parent;
        this.patterns = [];
        this.patternMap = {};
        this.patternObj = {};
    }
    Pattern.prototype = {
        constructor: Pattern,
        destroy: function () {
            this.parent = null;
            this.patterns.length = 0;
            this.patterns = null;
            this.patternMap = null;
            this.patternObj = null;
        },
        dispose: function () {
            this.ctx = null;
        },
        init: function (ctx) {
            this.ctx = ctx;
        },
        addPattern: function (obj) {
            if (!this.isHas(obj.id)) this.patterns.push(obj);
        },
        isHas: function (id) {
            var list = this.patterns;
            for (var i = 0; i < list.length; i++) {
                if (list[i].id === id) return list[i];
            }
            return false;
        },
        reset: function (obj) {
            this.patternMap["$" + obj.id] = null;
            var option = this.isHas(obj.id);
            if (!option) return;
            option.src = obj.src;
            option.repeat = obj.repeat;
            this.patternObj[obj.id] = null;
        },
        createPatternByStr: function (str, target) {
            if (str.indexOf("$") == 0) {
                str = str.slice(1);
                var obj = this.isHas(str);
                var img = this.parent.resource.getImage(obj.src);
                var repeatStr = canvasTool.patternRepeatList.indexOf(obj.repeat) === -1 ? "no-repeat" : obj.repeat;
                var pattern = this.ctx.createPattern(img, repeatStr);
                this.patternMap["$" + str] = pattern;
                if (this.patternObj[str]) {
                    if (this.patternObj[str].indexOf(target) === -1) this.patternObj[str].push(target);
                }
                else this.patternObj[str] = [target];
                return pattern;
            }
        },
        getUseById: function (id) {
            return this.patternObj[id].slice();
        },
        remove: function (value, target) {
            var list = this.data.patternObj[value];
            if (list) {
                var index = list.indexOf(target);
                if (index !== -1) list.splice(index, 1); 
            }
        }
    };

    App.define("pattern", {
        pattern: Pattern
    })
})